package com.example.test.exam;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.test.R;
import com.example.test.all_Myhelper.exam_Myhelper;
import com.example.test.all_Myhelper.test_Myhelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ceshi extends AppCompatActivity implements View.OnClickListener {
    public TextView timu_time;
    public TextView timu;
    public Button up,down;
    public RadioButton bt_A,bt_B,bt_C,bt_D;
    public RadioGroup single;
    public TextView number;
    public exam_Myhelper exam_myhelper;
    public test_Myhelper test_myhelper;
    public Chronometer jishi;//计时组件
    public int page=0;//题号
    public int iddd;//记录测试编号
    List<String> user_chance = new ArrayList<>();//设置用户当前所选每道题答案的集合
    List<Boolean> pd = new ArrayList<>();//判断当前题目是否已经选择
//    List<String> a= new ArrayList<>();
//    List<String> b = new ArrayList<>();
//    List<String> c = new ArrayList<>();
//    List<String> d = new ArrayList<>();
//    List<String> daan = new ArrayList<>();//每道题的答案
//    List<Integer> id = new ArrayList<>();//每道题的编号

    Timer tmr = new Timer();
    Timer tmr_main = new Timer();
    Date st = new Date();
    Date start = new Date(st.getTime()+8*60*60*1000);
    Date endtime_10mins = new Date(start.getTime()+600000);//1s=1000ms加10分钟   这里加的是时区问题
    Date endtime_1h = new Date(start.getTime()+3600000);
    Date endtime_2h = new Date(start.getTime()+7200000);
    SimpleDateFormat ft = new SimpleDateFormat("HH:mm:ss");
    Calendar calendar = Calendar.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.timu);
        tmr_main.schedule(new time(),st);
        int s = calendar.get(Calendar.SECOND);
        System.out.println(s);
//        tmr.scheduleAtFixedRate(new TimerTask() {
//            @Override
//            public void run() {
//                timu_time.setText("当前时间"+ft.format(System.currentTimeMillis()+8*60*60*1000));
////                System.out.println(ft.format(System.currentTimeMillis())+ "and" + ft.format(st.getTime()+6000));
////                if(ft.format(System.currentTimeMillis()).equals(ft.format(st.getTime() + 6000))){
////                    System.out.println("到地方啦");
////                    tmr.cancel();
////                    tmr_main.cancel();
////                }
//            }
//        },0,1000);
        exam_myhelper = new exam_Myhelper(this);
        test_myhelper = new test_Myhelper(this);
        init();
        chance();
        setTmr();
//        System.out.println("-------------"+test_id_to_timu_list());
//        sss();
    }

    public void init(){
        timu_time = (TextView) findViewById(R.id.timu_time);
        timu = (TextView) findViewById(R.id.timu);
        bt_A = (RadioButton) findViewById(R.id.A);
        bt_B= (RadioButton) findViewById(R.id.B);
        bt_C = (RadioButton) findViewById(R.id.C);
        bt_D = (RadioButton) findViewById(R.id.D);
        up = (Button) findViewById(R.id.up);
        down = (Button) findViewById(R.id.down);
        single = (RadioGroup) findViewById(R.id.single);
        number = (TextView) findViewById(R.id.number);
        jishi = (Chronometer) findViewById(R.id.jishi);

    }


    public int ttm(int t){//查找测试限时
        SQLiteDatabase db;
        int i=0;
        db = test_myhelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from test where id=?",new String[]{String.valueOf(t)});
        if(cursor.moveToFirst()){
            i = cursor.getInt(3);
        }
        cursor.close();
        db.close();
        return i;
    }

    public List<String> test_id_to_timu_list(){//从数据库中取出指定id号的测试的题目列表
        String list ;
        List<String> s= new ArrayList<>();//题目编号列表
        Bundle bundle = getIntent().getExtras();
        int postion = bundle.getInt("id");
        iddd = postion;
        System.out.println(postion);
        SQLiteDatabase db;
        db = test_myhelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from test where id=?",new String[]{String.valueOf(postion)});
        if(cursor.moveToFirst()){
            list = cursor.getString(2);
            String[] x= list.substring(1,list.length()-1).split(", ");
            for(int k =0;k<x.length;k++){
                s.add(x[k]);
            }
        }
        cursor.close();
        db.close();
        return s;
    }

    public List<String> A(List<String> abc,int postion){//返回题目title列表
        List<String> list = new ArrayList<>(abc);
        List<String> s = new ArrayList<>();
        SQLiteDatabase db;
        db = exam_myhelper.getReadableDatabase();
        for(int i=0;i<list.size();i++){
            Cursor cursor = db.rawQuery("select * from tiku where _id=?",new String[]{list.get(i)});
            if(cursor.moveToFirst()){
                s.add(cursor.getString(postion));
            }
            cursor.close();
        }
        db.close();
        return s;
    }

    public List<Integer> id_list(List<String> abc,int postion){//返回题目id列表
        List<String> list = new ArrayList<>(abc);
        List<Integer> s = new ArrayList<>();
        SQLiteDatabase db;
        db = exam_myhelper.getReadableDatabase();
        for(int i=0;i<list.size();i++){
            Cursor cursor = db.rawQuery("select * from tiku where _id=?",new String[]{list.get(i)});
            if(cursor.moveToFirst()){
                s.add(cursor.getInt(postion));
            }
            cursor.close();
        }
        db.close();
        return s;
    }



    public void chance(){
        Bundle bundle1 = getIntent().getExtras();
        int postion1 = bundle1.getInt("ceshi");
        timu_time.setText(String.valueOf(postion1));//传递事件参数
        List<String> title = new ArrayList<>(A(test_id_to_timu_list(),1));
        List<String> A = new ArrayList<>(A(test_id_to_timu_list(),2));
        List<String> B = new ArrayList<>(A(test_id_to_timu_list(),3));
        List<String> C = new ArrayList<>(A(test_id_to_timu_list(),4));
        List<String> D = new ArrayList<>(A(test_id_to_timu_list(),5));
        System.out.println(title+"...."+A+"...."+B+"....");
        for (int i=0;i<title.size();i++){
            user_chance.add("null");//初始化所有的用户选项为空
            pd.add(false);//初始化所有的题目都是未选择状态
        }
//        if(postion1==0){//10mins
//            yemian(page,title,A,B,C,D);//进入页面，传入的page为0
//        }else if(postion1==1){
//            yemian(page,title,A,B,C,D);//进入页面，传入的page为0
//        }else if(postion1==2){
//            yemian(page,title,A,B,C,D);//进入页面，传入的page为0
//        }
        yemian(page,title,A,B,C,D);//进入页面，传入的page为0
    }


    public void yemian(int s,List<String> title,List<String> A,List<String> B,List<String> C,List<String> D){
        System.out.println("当前是第"+s+"页");
        System.out.println("题目是："+title.get(s));
        System.out.println("选项内容："+"A:"+A.get(s)+"\t"+"B:"+B.get(s)+"\t"+"C:"+C.get(s)+"\t"+"D:"+D.get(s));
        timu.setText(title.get(s));//题目
        bt_A.setText(A.get(s));//A
        bt_B.setText(B.get(s));//B
        bt_C.setText(C.get(s));//C
        bt_D.setText(D.get(s));//D
        number.setText((s+1)+"/"+title.size());
        if(pd.get(s)==false){//如果未选择
            single.clearCheck();
            System.out.println("当前题目未选择！！！");
        }else if(pd.get(s)==true){//如果已经选择了保存选择序号到集合中
            System.out.println("题目已选择");
            switch (user_chance.get(s)) {
                case "A":
                    bt_A.setChecked(true);
                    break;
                case "B":
                    bt_B.setChecked(true);
                    break;
                case "C":
                    bt_C.setChecked(true);
                    break;
                case "D":
                    bt_D.setChecked(true);
                    break;
            }
        }
        System.out.println("NO----1");
        System.out.println("所有题目的选择状态："+pd);
        System.out.println("已选答案："+user_chance);
        single.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {//radiobutton监听
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                System.out.println("page="+s);
                if(checkedId == R.id.A){
                    if(s==page) {
                        user_chance.set(s, "A");
                        pd.set(s, true);
                    }else if(s>page){
                        int i = page;
                        user_chance.set(i,"A");
                    }
                }else if (checkedId == R.id.B){
                    if(s==page) {
                        user_chance.set(s, "B");
                        pd.set(s, true);
                    }else if(s>page){
                        int i = page;
                        user_chance.set(i,"B");
                    }
                }else if(checkedId == R.id.C){
                    if(s==page) {
                        user_chance.set(s, "C");
                        pd.set(s, true);
                    }else if(s>page){
                        int i = page;
                        user_chance.set(i,"C");
                    }
                }else if(checkedId == R.id.D){
                    if(s==page) {
                        user_chance.set(s, "D");
                        pd.set(s, true);
                    }else if(s>page){
                        int i = page;
                        user_chance.set(i,"D");
                    }
                }
                System.out.println("NO---2");
                System.out.println("所有题目的选择状态："+pd);
                System.out.println("已选答案："+user_chance);
            }
        });
        if(s==0){
            up.setVisibility(View.GONE);
        }else{
            up.setVisibility(View.VISIBLE);
            up.setText("上一题");
        }
        if(s==title.size()-1){
            down.setText("提交");
        }else{
            down.setText("下一题");
        }
//        System.out.println("ccccccccc"+id_list());
    }

    @Override
    public void onClick(View v) {
        List<String> title = new ArrayList<>(A(test_id_to_timu_list(),1));
        List<String> A = new ArrayList<>(A(test_id_to_timu_list(),2));
        List<String> B = new ArrayList<>(A(test_id_to_timu_list(),3));
        List<String> C = new ArrayList<>(A(test_id_to_timu_list(),4));
        List<String> D = new ArrayList<>(A(test_id_to_timu_list(),5));
        if(v.getId()==R.id.up){//上一页
            page--;
            System.out.println("点击上一页后page="+page);
            yemian(page,title,A,B,C,D);
        }else if(v.getId()==R.id.down && page==title.size()-1){//提交
            Toast.makeText(this,"提交成功",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(ceshi.this,result.class);
            Bundle bundle = new Bundle();//向result页面传递数据
            bundle.putStringArrayList("chance", (ArrayList<String>) user_chance);//用户选择集合
            bundle.putIntegerArrayList("id", (ArrayList<Integer>) id_list(test_id_to_timu_list(),0));//题目id集合
            bundle.putStringArrayList("daan", (ArrayList<String>) A(test_id_to_timu_list(),6));//每道题的答案的集合
            intent.putExtras(bundle);
            startActivity(intent);

        }else if(v.getId()==R.id.down){//下一页
            page++;
            System.out.println("点击下一页后page="+page);
            yemian(page,title,A,B,C,D);
        }
    }


    public void setTmr(){

        jishi.setBase(SystemClock.elapsedRealtime()+ttm(iddd)*1000);
        jishi.setFormat("%s");
        jishi.start();
        jishi.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {//倒计时
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                jishi.setText(jishi.getText().toString().substring(1));
                if(SystemClock.elapsedRealtime()-jishi.getBase()>=0){
                    page = test_id_to_timu_list().size()-1;
                    System.out.println("page"+ page);
                    Toast.makeText(ceshi.this,"时间到！",Toast.LENGTH_SHORT).show();
                    down.performClick();
                    jishi.stop();
                }
            }
        });
        up.setOnClickListener(this);
        down.setOnClickListener(this);
    }

}
